<template>
  <div class="mod_box">
    <modTabs :tabIndex="tabIndex"></modTabs>
    <el-row :gutter="20">
      <!-- <el-col :span="12">
        <el-select
          v-model="companyId"
          clearable
          filterable
          placeholder="请选择单位"
          style="width: 100%;"
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item, index) in company"
            :key="index"
          ></el-option>
        </el-select>
      </el-col>-->
      <el-col :span="12">
        <el-input v-model.trim="companyName" placeholder="输入单位名称" @keyup.enter.native="search"></el-input>
      </el-col>
      <el-col :span="12">
        <el-input v-model.trim="username" placeholder="输入名称" @keyup.enter.native="search">
          <el-button slot="append" @click="search">搜索</el-button>
        </el-input>
      </el-col>
    </el-row>

    <el-row class="mod_title">
      <el-col :sm="4">
        <div class="g-title">人员数目（{{total}}个）</div>
      </el-col>
      <el-col :sm="20" style="text-align: right;">
        <el-button type="primary" @click="add" size="small">新增</el-button>
        <el-button type="warning" @click="edit" size="small">修改</el-button>
        <!-- <el-button type="danger" @click="delUser(0)" size="small">禁用</el-button>
        <el-button type="success" @click="delUser(1)" size="small">启用</el-button>-->
        <el-button type="danger" @click="deleteUser" size="small">删除</el-button>
        <el-button type="primary" size="small" @click="fetchRoleList">分配角色</el-button>
        <el-button type="primary" @click="downloadTpl" size="small">模板下载</el-button>
        <el-button type="primary" @click="daoruType = true" size="small">导入</el-button>
        <el-button type="primary" @click="exportData" size="small">导出</el-button>
        <el-button type="warning" @click="AllexportData" size="small">全部导出</el-button>
      </el-col>
    </el-row>

    <el-table
      ref="multipleTable"
      :data="listData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      @filter-change="handleFilterChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号"></el-table-column>
      <el-table-column prop="username" label="姓名" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column prop="companyName" label="所属单位" width="120" align="center"></el-table-column>
      <el-table-column prop="zw" label="职务" align="center"></el-table-column>
      <el-table-column prop="mobile" label="手机号" width="120" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column prop="phone" label="办公电话" width="120" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column prop="loginname" label="默认账号" width="120" align="center"></el-table-column>
      <el-table-column prop="pwd" label="默认密码" width="120" align="center"></el-table-column>
      <el-table-column prop="deptName" label="内设机构" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column prop="roleNames" label="角色" show-overflow-tooltip align="center"></el-table-column>
      <!-- <el-table-column
        prop="roleNames"
        label="角色"
        align="center"
        :filters="searchs.roleNames"
        column-key="roleNames"
        width="200"
      ></el-table-column> -->
    </el-table>

    <el-row style="padding: 32px 16px;">
      <el-col>
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-size="pageSize"
          :total="total"
          :current-page="pageNo"
          @current-change="fetchData"
          @size-change="pageSizeChange"
        ></el-pagination>
      </el-col>
    </el-row>

    <el-dialog
      title="账号信息"
      ref="tableDialog"
      :visible.sync="dialogVisible"
      width="80%"
      v-if="dialogVisible"
    >
      <el-form :model="formData" label-width="100px" :rules="formRules" ref="form">
        <el-row>
          <el-col :sm="24">
            <el-form-item label="单位" prop="comId">
              <el-select
                v-model="formData.comId"
                filterable
                placeholder="请选择单位"
                style="width: 100%;"
                @change="fetchDeptList"
              >
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="(item) in company"
                  :key="item.comId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :sm="8">
            <el-form-item label="登录账户" prop="loginname">
              <el-input v-model="formData.loginname" :disabled="!addMode" placeholder="请输入登录账户"></el-input>
            </el-form-item>
          </el-col>
          <el-col :sm="8">
            <el-form-item label="登录密码" prop="pwd">
              <el-input v-model="formData.pwd" placeholder="请输入登录密码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :sm="8">
            <el-form-item label="姓名" prop="username">
              <el-input v-model="formData.username" placeholder="请输入姓名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :sm="8">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="formData.mobile" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :sm="8">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="formData.sex" placeholder="请选择性别" style="width: 100%;">
                <el-option label="男" :value="0"></el-option>
                <el-option label="女" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="8">
            <el-form-item label="内设机构" prop="deptId">
              <el-select v-model="formData.deptId" placeholder="请选择内设机构" style="width: 100%;">
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="(item) in deptList"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :sm="8">
            <el-form-item label="职务">
              <el-input v-model="formData.zw" placeholder="请输入职务"></el-input>
            </el-form-item>
          </el-col>
          <el-col :sm="8">
            <el-form-item label="单位电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入单位电话"></el-input>
            </el-form-item>
          </el-col>
          <el-col :sm="8">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer" style="text-align: left;">
        <el-button type="primary" @click="save">保存数据</el-button>
        <el-button @click="resetForm">重置表单</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="listDataSelected.length==1?'修改角色':'批量新增角色'"
      :visible.sync="roleDialogVisible"
      width="80%"
    >
      <el-form>
        <el-row>
          <el-col :sm="24">
            <el-form-item label="选择角色">
              <el-checkbox-group v-model="rolesmodel">
                <el-checkbox
                  v-for="role in roles"
                  :label="role.id"
                  :key="role.id"
                  :disabled="(userInfo.usertype==3?true:false)&&role.enname=='dwgly'"
                >{{role.name}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer" style="text-align: left;">
        <el-button type="primary" @click="saveRole">保存数据</el-button>
        <el-button @click="rolesmodel.splice(0)">重置表单</el-button>
      </span>
    </el-dialog>

    <el-dialog title="导入人员信息" :visible.sync="daoruType" width="70%">
      <el-upload
        ref="upload"
        class="upload_exl"
        drag
        :action="serverProjName+'common/webupload.shtml'"
        multiple
        :on-success="uploadSuccess"
        :on-exceed="onExceed"
        :limit="1"
        :on-remove="onRemove"
        :before-upload="beforeUpload"
      >
        <el-button type="primary" size="mini">请选择要上传的EXCEL</el-button>
      </el-upload>
      <br />
      <div style="text-align:center">
        <el-button type="primary" @click="daoru()">确认导入</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style lang="scss">
.mod_box {
  padding: 20px;
}
.mod_title {
  padding: 20px 0;
  .g-title {
    height: 20px;
    padding-left: 8px;
    line-height: 22px;
    font-size: 16px;
    font-weight: 400;
    border-left: 2px solid #f54e40;
    margin: 10px 0;
    display: inline-block;
  }
  .eluploadwrapper {
    display: inline-block;
    margin: 0 10px;
  }
}

.el-table th {
  background-color: #f5f7fa;
}

.el-dialog {
  -webkit-transform: none;
  transform: none;
  left: 0;
  position: relative;
  margin: 0 auto;
  background: #eef1f6;
  .el-dialog__body {
    background-color: #fff;
    margin: 0px 10px;
  }
}
.eluploadwrapper {
  display: inline-block;
  margin-left: 10px;
}
.upload_exl .el-upload,
.upload_exl .el-upload-dragger {
  width: 100%;
}

.upload_exl .el-upload-dragger .el-button {
  margin-top: 76px;
}
</style>
<script>
import { axios } from "@/api/axios";
import modTabs from "../../components/modTabs/index";
import { mapGetters } from "vuex";
export default {
  components: { modTabs },
  data: function () {
    return {
      tabIndex: "1",
      username: "",
      companyId: "",
      dialogVisible: false,
      roleDialogVisible: false,
      daoruType: false,
      companyName: "", //搜索的单位名称
      roleData: "", //角色
      total: 0,
      pageNo: 1,
      pageSize: 10,
      allCars: [],
      selectedCars: [],
      listData: [], //全部数据
      listDataSelected: [], //选中数据
      formData: null,
      fileurl: "",
      headers: {
        cookie: "",
      },
      //单位列表
      company: [],
      formRules: {
        comId: [
          {
            required: true,
            message: "请选择所属单位",
            trigger: "blur",
          },
        ],
        loginname: [
          {
            required: true,
            validator: this.checkName,
            trigger: "blur",
          },
        ],
        pwd: [
          {
            required: true,
            message: "请输入登录密码",
            trigger: "blur",
          },
          {
            min: 6,
            max: 12,
            message: "长度在 6 到 12 个字符",
            trigger: "blur",
          },
          {
            pattern: /^(\w){6,20}$/,
            message: "只能输入6-20个字母、数字、下划线",
          },
        ],
        username: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            validator: this.checkMobile,
            trigger: "blur",
          },
        ],
      },
      addMode: false, //是新增还是编辑模式
      //角色
      roles: [],
      rolesmodel: [], //角色
      serverProjName: "", //javaweb项目名
      deptList: [], //部门列表
      searchs: {
        roleNames: [],
      },
    };
  },
  created() {
    this.serverProjName = this.VUE_APP_BASE_API;
    this.companyId = this.userInfo.comid;
    this.fetchData();
    this.fetchDwList();
    this.roleList();
  },
  computed: {
    ...mapGetters(["userInfo", "selectedComIds"]),
  },
  watch: {
    //监听左侧单位勾选 重新获取数据
    selectedComIds() {
      this.pageNo = 1;
      this.fetchData();
    },
  },
  methods: {
    //表头搜索
    handleFilterChange(filters) {
      //角色
      if (filters["roleNames"]) {
        this.roleData = filters["roleNames"].join(",");
      }
      this.fetchData();
    },

    //导出
    AllexportData() {
      this.$confirm("是否全部导出?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        try {
          let loading = this.$loading({ text: "数据较多，请耐心等待" });
          let params = {
            pageNo: 1,
            pageSize: this.total,
            username: this.username,
            companyId: this.companyId,
            comIds: this.selectedComIds.join(","),
          };
          let data = await axios("/admin/yg/listJson.do", "get", params);
          loading.close();
          var alldata = data.data;
          var headers =
            "姓名,所属单位,职务,手机号,办公电话,默认账号,默认密码,内设机构,角色";
          var Outdata = alldata.map(function (e) {
            if (e.roleNames) {
              e.roleNames = e.roleNames.replace(/,/g, "，");
            }
            return {
              username: e.username || "",
              companyName: e.companyName || "",
              zw: e.zw || "",
              mobile: e.mobile || "",
              phone: e.phone || "",
              loginname: e.loginname || "",
              pwd: e.pwd || "",
              deptName: e.deptName || "",
              roleNames: e.roleNames || "",
            };
          });
          this.jsonToExcel(Outdata, headers);
        } catch (error) {
          loading.close();
        }
      });
    },
    //检查登录名合法性
    checkName(rule, value, callback) {
      if (!value || !value.trim() || value.length == 0) {
        callback(new Error("请输入登录账户"));
      }
      if (this.addMode == true) {
        var url = "/admin/checkName.do";
        axios(url, "get", {
          name: this.formData.loginname,
        }).then((data) => {
          if (data) {
            callback();
          } else {
            callback(new Error("账户已存在"));
          }
        });
      } else {
        callback();
      }
    },
    //检查手机号
    checkMobile(rule, value, callback) {
      if (!value || !value.trim() || value.length == 0) {
        callback(new Error("手机号不能为空"));
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
        if (reg.test(value)) {
          var url = "/admin/checkMobile.do";
          var params = {
            mobile: this.formData.mobile,
          };
          if (this.addMode == false) {
            var params = {
              mobile: this.formData.mobile + "@@" + this.formData.userid,
            };
          }
          axios(url, "get", params).then((data) => {
            if (data) {
              callback();
            } else {
              callback(new Error("手机号已存在"));
            }
          });
        } else {
          callback(new Error("请输入正确的手机号"));
        }
      }
    },
    openDialog() {
      this.dialogVisible = true;
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
    //获取单位列表
    fetchDwList() {
      var url = "/admin/yg/dwListJson.do";
      axios(url, "get", {
        companyId: this.userInfo.comid,
      }).then((data) => {
        this.company = data;
        this.deptList.splice(0, 0);
      });
    },
    //获取部门列表
    fetchDeptList(companyid) {
      var url = "/admin/yg/deptListJson.do";
      axios(url, "get", {
        companyid: companyid,
      }).then((data) => {
        this.deptList = data;
        this.deptList.splice(0, 0);
      });
    },
    //下载模板
    downloadTpl(files) {
      var form = document.createElement("form");
      form.setAttribute(
        "action",
        this.serverProjName + "upload/temp/人员导入模板.xlsx"
      );
      form.setAttribute("method", "get");
      document.body.append(form);
      form.submit();
    },
    beforeUpload(file) {
      var FileExt = file.name.replace(/.+\./, "");
      if (["xlsx"].indexOf(FileExt.toLowerCase()) === -1) {
        this.$message({
          type: "warning",
          message: "请上传后缀名为xlsx的文件！",
        });
        return false;
      }
    },
    uploadSuccess(file) {
      if (!file) return;
      console.log(file);
      if (file.error == 0) {
        console.log(this.VUE_APP_BASE_API + file.url);
        this.fileurl = file.url;
      } else {
        this.$message("上传失败，请重试");
      }
    },

    onRemove() {
      this.fileurl = "";
    },
    onExceed() {
      this.$message("只能上传1个文件，请先移除已上传文件再上传");
    },
    daoru() {
      if (this.fileurl == "") {
        this.$message("请上传文件");
        return;
      }
      let url = "/admin/yg/import.do";
      let params = { dir: this.fileurl };
      axios(url, "post", params).then((data) => {
        if (data.error == 0) {
          if (data.errorMsg) {
            data.errorMsg = data.errorMsg.replace(/^,+/, "").replace(/,+$/, "");
            this.$message({ message: data.errorMsg });
          } else {
            this.$message("导入成功");
          }
          this.fileurl = "";
          this.$refs.upload.clearFiles();
          this.fetchData();
          this.daoruType = false;
        } else {
          this.$message("导入失败，请重试");
        }
      });
    },
    //筛选中的角色
    roleList() {
      var url = "/admin/yg/roleListJson.do";
      axios(url, "get").then((data) => {
        data.map((value, index, arry) => {
          this.searchs.roleNames.push({ value: value.id, text: value.name });
        });
      });
    },
    //获取用户角色信息
    fetchRoleList() {
      if (this.listDataSelected.length == 0) {
        this.$message("请选择");
        return;
      }
      var params = {};
      if (this.listDataSelected.length == 1) {
        params.userid = this.listDataSelected[0].userid;
      }
      var url = "/admin/yg/roleListJson.do";
      axios(url, "get", params).then((data) => {
        this.roles = data;
        console.log(this.roles);
        this.rolesmodel = this.roles
          .map((e) => {
            if (e.checked) {
              return e.id;
            }
          })
          .filter(function (e) {
            return e;
          });
        this.rolesmodel.splice(0, 0);
        this.roleDialogVisible = true;
      });
    },
    //保存角色
    saveRole() {
      var url = "/admin/yg/batchSetRole.do";
      var params = new URLSearchParams();
      params.append(
        "userids",
        this.listDataSelected
          .map(function (e) {
            return e.userid;
          })
          .join(",")
      );
      params.append("roleids", this.rolesmodel.join(","));
      axios(url, "post", params).then((data) => {
        if (data.error == 0) {
          this.$message.success("修改成功");
          this.roleDialogVisible = false;
          //修改本地数据
          this.fetchData();
        } else {
          this.$message.error("操作失败");
        }
      });
    },
    //编辑用户信息
    edit() {
      if (this.listDataSelected.length == 0) {
        this.$message("请选择");
        return;
      }
      this.formData = {
        userid: this.listDataSelected[0].userid,
        loginname: this.listDataSelected[0].loginname,
        pwd: this.listDataSelected[0].pwd,
        username: this.listDataSelected[0].username,
        sex: this.listDataSelected[0].sex,
        mobile: this.listDataSelected[0].mobile,
        zw: this.listDataSelected[0].zw,
        phone: this.listDataSelected[0].phone,
        email: this.listDataSelected[0].email,
        deptName: this.listDataSelected[0].deptName,
        deptId: this.listDataSelected[0].depId * 1,
        companyName: this.listDataSelected[0].companyName,
        comId: this.listDataSelected[0].comid * 1,
      };
      console.log(this.formData);
      this.fetchDwList();
      this.fetchDeptList(this.formData.comId);
      this.addMode = false;
      this.dialogVisible = true;
    },
    //新增按钮事件
    add() {
      this.formData = {
        loginname: "",
        pwd: "",
        username: "",
        sex: 0,
        mobile: "",
        zw: "",
        phone: "",
        email: "",
        deptName: "",
        deptId: "",
        companyName: "",
        comId: "",
      };
      this.addMode = true;
      this.fetchDwList();
      this.dialogVisible = true;
    },
    //提交用户信息表单
    save() {
      this.$refs.form.validate((pass) => {
        if (!pass) {
          return;
        }
        this.formData["company.id"] = this.formData.comId;
        this.formData["dept.id"] = this.formData.deptId;
        var url = "/admin/yg/edit.do";
        if (this.addMode) {
          url = "/admin/yg/add.do";
        }
        axios(url, "post", this.formData).then((data) => {
          if (data.error == 0) {
            this.$message("操作成功");
            this.dialogVisible = false;
            this.fetchData();
          } else {
            this.$message("操作失败");
          }
        });
      });
    },
    //搜索
    search() {
      this.pageNo = 1;
      this.fetchData();
    },
    //导出
    exportData() {
      if (this.listDataSelected.length == 0) {
        this.$message("请选择");
        return;
      }
      var headers =
        "姓名,内设机构,职务,手机号,办公电话,角色,登录名,是否司机,注册日期,状态,密码";
      var data = this.listDataSelected.map(function (e) {
        return {
          username: e.username || "",
          deptName: e.deptName || "",
          zw: e.zw || "",
          mobile: e.mobile || "",
          phone: e.phone || "",
          roleNames: e.roleNames.replace(/,/g, "，"),
          loginname: e.loginname,
          dr: e.dr == 1 ? "是" : "否",
          registtime: e.registtime,
          zt: e.zt || "",
          pwd: e.pwd,
        };
      });
      this.jsonToExcel(data, headers);
    },
    //json导出excel
    jsonToExcel(jsonData, headers) {
      //列标题，逗号隔开，每一个逗号就是隔开一个单元格
      var str = headers + "\n";
      //增加\t为了不让表格显示科学计数法或者其他格式
      for (var i = 0; i < jsonData.length; i++) {
        for (var item in jsonData[i]) {
          str += jsonData[i][item] + "\t,";
        }
        str += "\n";
      }
      //encodeURIComponent解决中文乱码
      var uri = "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(str);
      //通过创建a标签实现
      var link = document.createElement("a");
      link.href = uri;
      //对下载的文件命名
      link.download = "导出数据表.csv";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    pageSizeChange(newSize) {
      this.pageSize = newSize;
      this.pageNo = 1;
      this.fetchData();
    },
    async fetchData(pageNo) {
      if (pageNo) {
        this.pageNo = pageNo;
      }
      let params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        username: this.username,
        companyName: this.companyName,
        comIds: this.selectedComIds.join(","),
        roleIds: this.roleData,
      };
      if (this.companyId != "") {
        params.companyId = this.companyId;
      }
      let data = await axios("/admin/yg/listJson.do", "get", params);
      // let Array = [];
      // data.data.forEach(function (e, inx1) {
      //   Array.push(e[0]);
      // });
      this.listData = data.data;
      this.total = data.total;
      this.listDataSelected.splice(0);
    },
    //表格多选
    handleSelectionChange(val) {
      this.listDataSelected.splice(0);
      val.forEach((e) => {
        this.listDataSelected.push(e);
      });
      console.log(this.listDataSelected);
    },
    //禁用启用
    async delUser(status) {
      console.log(status);
      if (this.listDataSelected.length == 0) {
        this.$message("请选择");
        return;
      }
      let url = "/admin/delUsers.do";
      if (status == 1) {
        url = "/admin/startUsers.do";
      }
      let userIds = this.listDataSelected
        .map(function (e) {
          return e.userid;
        })
        .join(",");
      let data = await axios(url, "get", { uIds: userIds });
      if (data.error == 0) {
        this.listDataSelected.forEach(function (e) {
          e.status = status;
          e.zt = status == 1 ? "正常" : "禁用";
        });
      } else {
        this.$message.warning("操作失败");
      }
    },

    //删除
    deleteUser() {
      if (this.listDataSelected.length == 0) {
        this.$message("请选择");
        return;
      }
      this.$confirm("是否确定删除账号?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let roleNamesData = "";
          this.listDataSelected.forEach((e) => {
            roleNamesData += e.roleNames + ",";
          });
          let num = roleNamesData.indexOf("单位管理员");
          console.log(num);
          if (num != -1 && this.companyId != "") {
            this.$message.error(
              "选择删除的账号中包括单位管理员，请重新选择删除"
            );
            return;
          }
          let url = "/admin/delUsers.do";
          let userIds = this.listDataSelected
            .map(function (e) {
              return e.userid;
            })
            .join(",");

          axios(url, "get", { uIds: userIds }).then((data) => {
            if (data.error == 0) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.fetchData();
            } else {
              this.$message.warning("操作失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>